import axios from 'axios';
import { ElNotification } from 'element-plus';//ElMessageBox
import sysConfig from "@/config";
import tool from '@/utils/tool';
import router from '@/router';
import i18n from '../locales'

axios.defaults.baseURL = ''

axios.defaults.timeout = sysConfig.TIMEOUT

const lang = {"zh_CN": "zh-CN","en_US":"en-US", "ja_JP":"ja_JP"}
// HTTP request 拦截器
axios.interceptors.request.use(
	(config) => {
		let token = tool.cookie.get("TOKEN");
		let aid = tool.cookie.get("AID");
		const isS3 = config.url&&config.url.includes('s3.ap-northeast-1.amazonaws.com')
		if(isS3)return config
		if(token){
			config.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token;
			config.headers['X-Adminid'] = aid;
		}
		config.headers[sysConfig.LANG_NAME] = (localStorage.getItem('APP_LANG')&&lang[JSON.parse(localStorage.getItem('APP_LANG')).content]) || lang[sysConfig.LANG]
		if(!sysConfig.REQUEST_CACHE && config.method == 'get'){
			config.params = config.params || {};
			// config.params['_'] = new Date().getTime();
		}
		Object.assign(config.headers, sysConfig.HEADERS)
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

//FIX 多个API同时401时疯狂弹窗BUG
// let MessageBox_401_show = false

// HTTP response 拦截器
axios.interceptors.response.use(
	(response) => {
		return response;
	},
	(error) => {
		if (error.response) {
			console.log('serve code: ',error.response)
			// if(error.response.config.url.includes('checkIn'))return;
			if(error.response.data.code&&error.response.data.code != '500' && error.response.data.code != '400' && error.response.data.code != '404' && error.response.data.code != '401' && error.response.data.code != '40101' && error.response.data.code != 'NG') {
				return error.response
			} else if (error.response.status == 404 || error.response.status == 400) {
				ElNotification.error({
					title: i18n.global.messages[i18n.global.locale].serve.error,
					message: error.response.data.message || `Status:404，${i18n.global.messages[i18n.global.locale].serve.message}`
				});
			} else if (error.response.status == 500) {
				ElNotification.error({
					title: i18n.global.messages[i18n.global.locale].serve.error,
					message: error.response.data.message || `Status:500，${i18n.global.messages[i18n.global.locale].serve.errMessage}`
				});
			} else if (error.response.status == 401) {
				// if(!MessageBox_401_show){
					// MessageBox_401_show = true
					if(error.response.data.code == '40101'){
						if(tool.cookie.get("TOKEN")){
							router.replace({path: '/login'});
						}
						ElNotification.error({
							title: i18n.global.messages[i18n.global.locale].serve.error,
							message: error.response.data.message
						});
						return error.response
					} else {
						ElNotification.error({
							title: i18n.global.messages[i18n.global.locale].serve.error,
							message: error.response.data.message
						});
						// MessageBox_401_show = false
					}
				// }
			} else {
				ElNotification.error({
					title: i18n.global.messages[i18n.global.locale].serve.error,
					message: error.message || error.response.data.message || `Status:${error.response.status}，${i18n.global.messages[i18n.global.locale].serve.wrong}`
				});
			}
		} else {
			ElNotification.error({
				title: i18n.global.messages[i18n.global.locale].serve.error,
				message: i18n.global.messages[i18n.global.locale].serve.noResponse
			});
		}

		return Promise.reject(error.response||error.message||i18n.global.messages[i18n.global.locale].serve.timeOut);
	}
);

var http = {

	/** get 请求
	 * @param  {string} url 接口地址
	 * @param  {object} params 请求参数
	 * @param  {object} config 参数
	 */
	get: function(url, params={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'get',
				url: url,
				params: params,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** post 请求
	 * @param  {string} url 接口地址
	 * @param  {object} data 请求参数
	 * @param  {object} config 参数
	 */
	post: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** put 请求
	 * @param  {string} url 接口地址
	 * @param  {object} data 请求参数
	 * @param  {object} config 参数
	 */
	put: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'put',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** patch 请求
	 * @param  {string} url 接口地址
	 * @param  {object} data 请求参数
	 * @param  {object} config 参数
	 */
	patch: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'patch',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** delete 请求
	 * @param  {string} url 接口地址
	 * @param  {object} data 请求参数
	 * @param  {object} config 参数
	 */
	delete: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'delete',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** jsonp 请求
	 * @param  {string} url 接口地址
	 * @param  {string} name JSONP回调函数名称
	 */
	jsonp: function(url, name='jsonp'){
		return new Promise((resolve) => {
			var script = document.createElement('script')
			var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
			script.id = _id
			script.type = 'text/javascript'
			script.src = url
			window[name] =(response) => {
				resolve(response)
				document.getElementsByTagName('head')[0].removeChild(script)
				try {
					delete window[name];
				}catch(e){
					window[name] = undefined;
				}
			}
			document.getElementsByTagName('head')[0].appendChild(script)
		})
	}
}

export default http;
